package com.example.demo;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * @author zhouyunzhi
 * 模拟同步转异步的controller
 */
@RestController
public class APIController {

	@Autowired
	sendTaskSvc svc;
	static Map<String,DeferredResult<String>> holder = new ConcurrentHashMap<String,DeferredResult<String>>();
//	此方法被请求后会被挂起，等待处理完毕或者超时
	@RequestMapping(value="api/sayHi")
	@ResponseBody
	public DeferredResult<String> sayHi(String name){
		DeferredResult<String> df = new DeferredResult<String>(10000L);//超时时间10s 超时则反回null
		//异步操作处理完成时会调用
		df.onCompletion(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("完成任务");
			}
		});
		synchronized(holder) {
			holder.put("1", df);
		}
		System.out.println("put到队列");
		
		return df;//这里不会立即返回response 而是将线程挂起，直到超时或者被其他线程唤醒
	}
    @RequestMapping("/set")
    public String setDeferredResult() {
    	synchronized(holder) {
    		DeferredResult<String> df=holder.get("1");
    		df.setResult("Hi world");
    	}
        return "succeed";
    }

}
